package icu.lookyousmileface.generatorandconsumer;

/**
 * @author starrysky
 * @title: GeneraAndConsumerSync
 * @projectName Juc_Pro
 * @description: sync版本生产者和消费者
 * @date 2021/1/299:11 上午
 * 线程之间的通信问题：生产者和消费者问题！ 等待唤醒，通知唤醒
 * 线程交替执行 A B 操作同一个变量 num = 0
 * A num+1
 * B num-1
 */
public class GeneraAndConsumerSync {
    public static void main(String[] args) {
        // 资源类
        Data data = new Data();
        //线程
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.inc();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
        new Thread(()->{
            for (int i = 0; i < 50; i++) {
                try {
                    data.dec();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
    }
}
class Data{
    private int number = 0;

    public synchronized void inc() throws InterruptedException {
        while (number!=0){
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName()+":"+"number:"+number);
        //唤醒所有线程
        this.notifyAll();
    }

    public synchronized void dec() throws InterruptedException {
        while (number==0){
            //等待唤醒。睡眠
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName()+":"+"number:"+number);
        this.notifyAll();
    }
}
